package com.podcstr.controller;

import com.podcstr.entity.Category;
import com.podcstr.entity.Podcast;
import com.podcstr.service.CategoryService;
import com.podcstr.service.PodcastService;
import com.podcstr.service.exception.ServiceException;
import org.apache.log4j.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @author azim
 * @since 5/19/13 
 */

@Named
@SessionScoped
public class CategoryController implements Serializable {

    private final Logger log = Logger.getLogger(PodcastController.class.getName());
    private Category category;

    private List<Podcast> podcasts;
    private List<Category> parents;
    private List<Category> categories;

    @EJB
    private CategoryService categoryService;

    @EJB
    private PodcastService podcastService;

    @PostConstruct
    public void init() {

        //collecting the entire categories list from service

        categories = categoryService.findAll();

        //Formatting each category name for viewing

        for (Category category1 : categories) {

            if (category1.getParent() != 0) {
                category1.setName(categoryService.findCategoryById(category1.getParent()).getName() + "-" + category1.getName());
            }
        }

        //Sorting the entire categories by name

        Collections.sort(categories, Category.CompareByName);

        //collecting the parent categories list from service

        parents = categoryService.findParentCategories();

        //Sorting the parent categories by name

        Collections.sort(parents, Category.CompareByName);
    }

    //Getters and setters for category controller

    public Category getCategory() {

        return category;
    }

    public void setCategory(Category category) {

        this.category = category;
    }

    public List<Category> getCategories() {

        return categories;
    }

    public List<Category> getParents() {
        return parents;
    }

    private List<Category> getChilds(long parentId) {

        //collecting the child categories list from service bu parent id

        List<Category> childs = categoryService.findChildCategories(parentId);

        //Sorting the child categories by name

        if(childs.size()!= 0)
        {
            Collections.sort(childs, Category.CompareByName);
        }

        return childs;
    }

    public void setCategoryService(CategoryService categoryService) {

        this.categoryService = categoryService;
    }

    public void setPodcastService(PodcastService podcastService) {

        this.podcastService = podcastService;
    }

    public List<Podcast> getPodcasts() {

        return podcasts;
    }

    //Other methods for category controller

    public String showAddForm() {

        category = new Category();

        return "login_add_category.xhtml?faces-redirect=true";
    }

    public void sort(String sortBy) {

        log.info("in the sort." + sortBy);

        if (sortBy.equals("recent")) {

            Collections.sort(podcasts, Podcast.CompareByDateCreated);
            Collections.reverse(podcasts);
        } else if (sortBy.equals("alphabetical")) {

            Collections.sort(podcasts, Podcast.CompareByName);
        } else {

            Collections.sort(podcasts, new Comparator<Podcast>() {
                @Override
                public int compare(Podcast o1, Podcast o2) {

                    return ((Long) (o1.getRating())).compareTo(((Long) (o2.getRating())));
                }
            });
            Collections.reverse(podcasts);
        }

    }

    public void add() {

        FacesContext context = FacesContext.getCurrentInstance();
        if (category != null) {

            try {

                categoryService.add(category);

                //Checking if it is a parent category or not and if it is adding it to the parent list

                if (category.getParent() == 0) {
                    parents.add(category);
                    Collections.sort(parents, Category.CompareByName);
                } else {
                    category.setName(categoryService.findCategoryById(category.getParent()).getName() + "-" + category.getName());
                }

                //Adding category to the categories list and re-sort the list

                categories.add(category);

                Collections.sort(categories, Category.CompareByName);

                context.addMessage(null, new FacesMessage("Successfully Added The '" + category.getName() + "' category."));

            } catch (ServiceException e) {

                if (e.getViolations().size() != 0) {
                    context.addMessage(null, new FacesMessage(e.getViolations().toString()));
                }
                context.addMessage(null, new FacesMessage(e.getMessage()));
            }
        }

        showAddForm();
    }

    public String showPodcastUnderCategory(String id) throws IOException {

        long categoryId = Long.parseLong(id);
        podcasts = podcastService.findByCategoryId(categoryId);
        category = categoryService.findCategoryById(categoryId);
        if (podcasts == null) {

            podcasts = new ArrayList<Podcast>();
        }

        return null;

    }


}
